<template>
   <div class="app-container">
        <!-- 搜索栏 -->
        <el-form @submit.native.prevent :inline="true" v-show="showSearch">
            <el-form-item label="相册名称">
                <el-input v-model="queryParams.keyword" style="width: 200px" placeholder="请输入相册名称" clearable
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            </el-form-item>
        </el-form>
        <!-- 操作按钮 -->
        <el-row :gutter="10" class="mb15">
            <el-col :span="1.5">
                <el-button type="primary" plain class="el-icon-plus" @click="handleAdd">新建</el-button>
            </el-col>
            <RightToolBar @changeShow="changeShowSearch" :showSearch="showSearch" @queryTable="getList"></RightToolBar>
        </el-row>
        <!-- 相册列表 -->
        <el-row :gutter="12" v-loading="loading">
            <el-empty v-if="albumList === null" description="暂无相册" />
            <el-col v-for="album of albumList" :key="album.id" :xs="12" :sm="12" :lg="6">
                <div class="album-item" @click="checkPhoto(album.id)">
                    <div class="album-operation">
                        <el-dropdown @command="handleCommand">
                             <span class="el-dropdown-link write">
                              <i class="el-icon-arrow-down el-icon-more"></i>
                              </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item :command="'update,' + album.id">编辑</el-dropdown-item>
                                    <el-dropdown-item :command="'delete,' + album.id">删除</el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </div>
                    <el-image class="album-cover" fit="cover" :src="album.albumCover">
                    </el-image>
                    <div class="photo-count">
                        <div>{{ album.photoCount }}</div>
                        <el-icon v-if="album.status === 2">
                            <Hide />
                        </el-icon>
                    </div>
                    <div class="album-name">{{ album.albumName }}</div>
                </div>
            </el-col>
        </el-row>
        <!-- 分页 -->
        <el-pagination class="pagination-container" v-model:current-page="queryParams.current"
            v-model:page-size="queryParams.size" :hide-on-single-page="true" layout=" prev, pager, next" :total="count"
            @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
        <!-- 添加或修改对话框 -->
        <el-dialog :title="title" :visible.sync="addOrUpdate" width="550px" append-to-body>
            <el-form ref="albumFormRef" label-width="100px" :model="albumForm" :rules="rules">
                <el-form-item label="相册名称" prop="albumName">
                    <el-input placeholder="请输入相册名称" v-model="albumForm.albumName" style="width: 250px;" />
                </el-form-item>
                <el-form-item label="相册描述" prop="albumDesc">
                    <el-input placeholder="请输入相册描述" v-model="albumForm.albumDesc" style="width: 250px;" />
                </el-form-item>
                <el-form-item label="相册封面" prop="albumCover">
                  <el-upload drag :show-file-list="false" :headers="authorization" action="/api/admin/album/upload"
                    :on-progress="handleProgress"
                      accept="image/*" :before-upload="beforeUpload" :on-success="handleSuccess">
                      <i class="el-icon-upload" v-if="albumForm.albumCover === ''"></i>
                      <div class="el-upload__text" v-if="albumForm.albumCover === ''">
                          将文件拖到此处，或<em>点击上传</em>
                      </div>
                      <img v-else :src="albumForm.albumCover" width="360" />
                       <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过1MB</div>
                  </el-upload>
                   <el-progress v-if="progressFlag" :percentage="uploadPercentage"></el-progress>
              </el-form-item>
                <el-form-item label="发布形式">
                    <el-radio-group v-model="albumForm.status">
                        <el-radio :label="1">公开</el-radio>
                        <el-radio :label="2">私密</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="addOrUpdate = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { getToken } from '@/utils/auth';
import {getAlbumList, addAlbum, deleteAlbum, editAlbum, updateAlbum} from '@/api/album'
export default {
  data() {
    return {
      count: 0,
      showSearch: true,
      loading: false,
      title: "",
      addOrUpdate: false,
      progressFlag: false, // 是否显示进度条
       uploadPercentage: 0, // 上传进度
      queryParams: {
          current: 1,
          size: 10,
      },
      albumForm: {
        albumName:'',
        albumDesc:'',
        albumCover:'',
      },
      albumList: [],
      rules:{
        albumName: [
          { required: true, message: "请输入相册名称", trigger: "blur" },
        ],
        albumDesc: [
          { required: true, message: "请输入相册描述", trigger: "blur" },
        ],
        albumCover: [
          { required: true, message: "请上传相册封面", trigger: "blur" },
        ],
      }
    }
  },
  methods: {
    getList(){
      this.loading = true;
      getAlbumList(this.queryParams).then(res => {
        this.loading = false;
        this.albumList = res.data.recordList;
        this.count = res.data.count;
      })
    },
    submitForm(){
      this.$refs.albumFormRef.validate(valid => {
        if (valid) {
          if(this.albumForm.id){
            this.title = "编辑相册";
             this.progressFlag = false;
            updateAlbum(this.albumForm).then(res => {
              if(res.code == 200)
              {
                this.$message({type:'success',message:'操作成功'})
                this.addOrUpdate = false;
                this.getList();
                this.albumForm = {
                  albumName:'',
                  albumDesc:'',
                  albumCover:'',
                }
              }
            });
          }else{
            this.title = "新建相册";
            this.progressFlag = false;
            addAlbum(this.albumForm).then(res => {
            this.$message({type:'success',message:'操作成功'})
            this.addOrUpdate = false;
            this.getList();
            this.albumForm = {
              albumName:'',
              albumDesc:'',
              albumCover:'',
            }
          })
          }
       
        }else{
          return false;
        }
      });
    
    },
    handleQuery(){},
    changeShowSearch(data){
      this.showSearch = data;
    },
    queryTable(){},
    handleCurrentChange(){},
    handleAdd(){
      this.title = "新建相册";
       this.progressFlag = false;
      this.addOrUpdate = true;      
      this.albumForm = {
        albumName:'',
        albumDesc:'',
        albumCover:'',
      }
    },
        //上传进度
     handleProgress(event, file, fileList) {
      this.progressFlag = true; // 显示进度条
      // 计算上传进度
      this.uploadPercentage = event.percent
      if(event.percent >= 99)
      {
        this.uploadPercentage = 99
      }
    },
    handleSizeChange(){},
    beforeUpload(file){
   // 获取文件大小，单位为字节
      const fileSize = file.size;
      // 允许的文件类型数组
      const allowedTypes = ['image/png', 'image/jpeg', 'image/jpg'];
      // 文件类型不在允许的类型列表中
      if (!allowedTypes.includes(file.type)) {
        this.$message.error('只能上传jpg/png文件');
        return false; // 终止上传
      }
      let commonSize = 1024*1024*10;
      // 文件大小超过1MB
      if (fileSize > commonSize) {
        this.$message.error('文件大小不能超过10MB');
        return false; // 终止上传
      }
      return true; // 允许上传
    },
    //上传成功
    handleSuccess(response, file){
      this.uploadPercentage = 100
      this.albumForm.albumCover = response.data
      this.$message({
        type: 'success',
        message: '上传成功!'
      })
    },
    handleCommand(command){
      const parts = command.split(",");
      let type = parts[0];
      let id = parts[1];
      if(type == 'update'){
        this.title = "编辑相册";
        editAlbum(id).then(res => {
          if(res.code == 200){
          this.albumForm = res.data;
          this.addOrUpdate = true;
          }
        })

      }
      if(type == 'delete'){
        this.title = '删除相册';
        this.$confirm('此操作将永久删除该相册, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteAlbum(id).then(res => {
            this.$message({type:'success',message:'操作成功'})
            this.getList();
          })
        }).catch(() => {
          this.$message({type:'info',message:'已取消删除'})
        });
      }
    },
    checkPhoto(albumId){
      this.$router.push({path:`/web/photo/${albumId}`})
    },
  },
  computed:{
    authorization() {
      const token = getToken()
      return {token}
    },
  },
  mounted(){
    this.getList();
  }
}
</script>

<style>
.album-item {
    position: relative;
    cursor: pointer;
    margin-bottom: 1rem;

    .album-operation {
        position: absolute;
        top: 0.5rem;
        right: 0.8rem;
        z-index: 9;
    }

    .album-cover {
        position: relative;
        border-radius: 4px;
        width: 100%;
        height: 170px;

        &:before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
        }
    }

    .photo-count {
        position: absolute;
        left: 0;
        right: 0;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 1.5rem;
        padding: 0 0.5rem;
        bottom: 2.6rem;
        color: #fff;
    }

    .album-name {
        text-align: center;
        margin-top: 0.5rem;
    }
}
.write{
    display: inline-block;
    position: relative;
    color: #ffffff;
    font-size: 14px;
}
</style>